package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.biz.user.UserContext;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.convention.result.Result;
import com.nageoffer.shortlink.admin.dao.entity.GroupDO;
import com.nageoffer.shortlink.admin.dao.mapper.GroupMapper;
import com.nageoffer.shortlink.admin.dto.req.GroupSortReqDTO;
import com.nageoffer.shortlink.admin.dto.req.GroupUpdateReqDTO;
import com.nageoffer.shortlink.admin.dto.resp.GroupListRespDTO;
import com.nageoffer.shortlink.admin.remote.ShortLinkActualRemoteService;
import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkCountQueryRespDTO;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.toolkit.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.nageoffer.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

/**
 * 短链接接口实现层
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    private final RedissonClient redissonClient;
    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNUm;

    @Override
    public void saveGroup(String name) {
        // 通过上下文得到username
        saveGroup(UserContext.getUsername(), name);
    }

    @Override
    public void saveGroup(String username, String name) { // 为了应对无法从用户上下文中获得username，eg：注册时
        // 使用分布式锁，保证线程安全
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            // 首先检查是否还能创建新的分组
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNUm) {
                throw new ClientException(String.format("已经超过最大分组：%d", groupMaxNUm));
            }

            // 创建新分组
            String gid;
            while(true) { // 生成不重复的新gid
                gid = RandomUtil.generateRandom();
                if (gidIsAvailable(username, gid)) {
                    break;
                }
            }
            GroupDO groupDO = GroupDO.builder()
                    .name(name)
                    .username(username)
                    .gid(gid)
                    .sortOrder(0)
                    .build();
            baseMapper.insert(groupDO);
        } finally {
            lock.unlock();
        }

    }

    @Override
    public List<GroupListRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        List<GroupDO> list = baseMapper.selectList(queryWrapper);
        // 从这里开始到返回，tmd真难啊
        Result<List<ShortLinkCountQueryRespDTO>> listResult =
                shortLinkActualRemoteService.listGroupShortLinkCount(list.stream().map(GroupDO::getGid).toList());
        List<GroupListRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(list, GroupListRespDTO.class);
        shortLinkGroupRespDTOList.forEach(each -> {
            Optional<ShortLinkCountQueryRespDTO> first = listResult.getData().stream()
                    .filter(item -> Objects.equals(item.getGid(), each.getGid())) // 过滤
                    .findFirst(); // 拿到第一个满足条件的元素，并封装到Optional容器
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }

    @Override
    public void updateGroup(GroupUpdateReqDTO requestParam) {
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0) // 根据有效状态
                .eq(GroupDO::getUsername, UserContext.getUsername()) // 根据username
                .eq(GroupDO::getGid, requestParam.getGid()); // 根据gid
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName()); // 更新分组名称
        baseMapper.update(groupDO, updateWrapper); // 在数据库执行该更新
    }

    @Override
    public void deleteGroup(String gid) { // 并不是直接从数据库删除，而是进行软删除，
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0) // 根据有效状态
                .eq(GroupDO::getUsername, UserContext.getUsername()) // 根据username
                .eq(GroupDO::getGid, gid); // 根据gid
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1); // 1 表示已删除
        baseMapper.update(groupDO, updateWrapper); // 在数据库执行该更新
    }

    @Override
    public void sortGroup(List<GroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            // 构建更新条件
            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            // 数据库中更新
            baseMapper.update(groupDO, updateWrapper);
        });
    }

    /**
     * 判断gid是否可用
     * @param gid 分组名
     * @return 可用返回true 不可用返回false
     */
    private Boolean gidIsAvailable(String username, String gid) {
        // 保证插入的gid要唯一，否则数据库插入失败
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO groupDO = baseMapper.selectOne(queryWrapper);
        return groupDO == null;
    }
}
